from apps.common.base.views import *
from project.settings import BASE_DIR
import subprocess

class BaseLzpayViewSet(BaseViewSet):
    # 签名类型
    signType = "SM2"
    # 序列号
    signSN = "4919305285"
    # 加密序列号
    encryptSN = "4776575245 "
    # 证书密码
    certPwd = "xlmp666888"
    # 平台账户
    merchantNo = "10200074"
    # 账户号
    subMerchantNo = "10200074"
    pubKeyPath = os.path.join(BASE_DIR, 'apps', 'pay', 'lzpay', 'cert', 'sm', 'lzpay_4776575245_SM2_SignCert.cer')
    pfxPath = os.path.join(BASE_DIR, 'apps', 'pay', 'lzpay', 'cert', 'sm', '4919305285_SM2_PrivateKey.sm2')

    # # 签名类型
    # signType = "SM2"
    # # 序列号
    # signSN = "4037020766"
    # # 加密序列号
    # encryptSN = "4037020766"
    # # 证书密码
    # certPwd = "123456"
    # # 平台账户
    # merchantNo = "10200002"
    # # 账户号
    # subMerchantNo = "30100002"
    # pfxPath = os.path.join(BASE_DIR, 'apps', 'pay', 'lzpay', 'cert', 'sm', '4037020766_SM2_PrivateKey.sm2')

    def getSign(self, r_params):
        data = self.signParamSplicing(r_params)
        jar_path = os.path.join(BASE_DIR, 'apps', 'pay', 'lzpay', 'Main.jar')
        args = ['java', '-jar', jar_path, 'sign', self.pfxPath, self.certPwd, data]
        result = subprocess.run(args, capture_output=True, text=True)
        # 输出程序输出
        # print('sign标准输出:', result.stdout.split('\n'))
        result_arr = result.stdout.split('\n')
        sign = ''
        if result.returncode == 0 and len(result_arr) > 1:
            sign = result_arr[len(result_arr)-2]
        return sign
    
    def encrypt(self, encrypt_data1, encrypt_data2):
        jar_path = os.path.join(BASE_DIR, 'apps', 'pay', 'lzpay', 'Main.jar')
        args = ['java', '-jar', jar_path, "encrypt", self.pubKeyPath, encrypt_data1, encrypt_data2]
        result = subprocess.run(args, capture_output=True, text=True)
        # 输出程序输出
        # print('加密标准输出:', result.stdout.split('\n'))
        result_arr = result.stdout.split('\n')
        encrypt_data = {}
        if result.returncode == 0 and len(result_arr) > 1:
            encrypt_data['data1'] = result_arr[len(result_arr)-4]
            encrypt_data['data2'] = result_arr[len(result_arr)-3]
            encrypt_data['digitalEnvelope'] = result_arr[len(result_arr)-2]
        return encrypt_data

    def signParamSplicing(self, paramMap):
        keySet = paramMap.keys()
        keyArray = list(keySet)
        keyArray.sort()
        data = []
        for paramKey in keyArray:
            if paramKey == "sign":
                continue
            value = paramMap.get(paramKey)
            if value is not None and value != "" and value != "null":
                data.append(f"{paramKey}={value}")
        return "&".join(data)